package com.best.Reference;

import java.lang.ref.SoftReference;

/**
 * @author Jiang Akang
 * employeeId: BG435424
 * @date 2020/12/11
 **/
public class SoftReferenceDemo {
    /**
     * 内存够用的时候就保留，不够用就回收
     */
    @SuppressWarnings("all")
    public static void softRefMemoryEnough() {
        Object o1 = new Object();
        SoftReference<Object> softReference = new SoftReference<>(o1);
        System.out.println("********GC前*********");
        System.out.println(o1);
        System.out.println(softReference.get());

        o1 = null;
        System.gc();

        System.out.println();
        System.out.println("********GC后*********");
        System.out.println(o1);
        System.out.println(softReference.get());
    }

    /**
     * JVM配置，故意产生大对象并配置小的内存，让它内存不够用了导致OOM，看软引用的回收情况
     * -Xms5m -Xmx5m -XX:+PrintGCDetails
     */
    @SuppressWarnings("all")
    public static void softRefMemoryNotEnough() {
        Object o1 = new Object();
        SoftReference<Object> softReference = new SoftReference<>(o1);
        System.out.println("********内存够用*********");
        System.out.println(o1);
        System.out.println(softReference.get());

        o1 = null;

        try {
            byte[] bytes = new byte[30 * 1024 * 1024]; //给5m，new了30m，自动触发GC
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            System.out.println();
            System.out.println("********内存不够用*********");
            System.out.println(o1);
            System.out.println(softReference.get());
        }
    }

    public static void main(String[] args) {
//        softRefMemoryEnough();
        softRefMemoryNotEnough();
    }
}
